import { ref, inject, watch, watchEffect } from 'vue';

function createField(props, emit, defaultValue) {
  let value = ref(props.modelValue ?? defaultValue);
  const ctx = inject('CMFormContext', null);
  const data = ctx?.form ?? {};
  const formItem = inject('CMFormItemContext', null);
  const name = formItem?.name || props.name;
  const formInitValue = data && name ? data[name] : undefined;
  if (formInitValue != undefined) {
    value.value = formInitValue;
  }
  watch(() => props.modelValue, val => {
    value.value = val;
  });
  watchEffect(() => {
    const val = value.value;
    emit('update:modelValue', val);
    if (!props.notCreateFiled) {
      ctx?.onChange(name, val);
    }
  });
  return value;
}

export { createField as default };
